<?php

namespace app\controller\api;

use app\BaseController;
use app\model\StationBasic;
use app\model\StationPrice;
use app\model\Stations;
use think\facade\Db;
use think\response\Json;

class Station extends BaseController
{
    public function lst(): Json
    {
        return $this->handle(function () {
            return $this->app->make(StationBasic::class)->userStation();
        });
    }

    public function detail(): Json
    {
        return $this->handle(function () {
            $param = request()->param();
            $file = "*";
            if (!empty($param['lat']) && !empty($param['lng']) && is_numeric($param['lat']) && is_numeric($param['lng'])) {
                $file = ['*', Db::raw("ST_Distance_Sphere(address_location, ST_GeomFromText('POINT({$param['lng']} {$param['lat']})')) AS distance")];
            }
            $st = $this->app->make(StationBasic::class);
            $user = $this->request->user;
            $data = $st->where('id', $param['id'])->field($file)->findOrEmpty()->toArray();
            $data['distance'] = !empty($data['distance']) ? (float)bcdiv($data['distance'], 1000, 2) : 0;
            $oil = $this->app->make(StationPrice::class)->with(['oil'])->where('station_id',$data['id'])->order('sup_id asc')->select()->toArray();
            $sup_id = $user['supplier'] ?? 0;
            $data['oil'] = [];
            if(!empty($oil)){
                foreach ($oil as $value){
                    if($value['sup_id'] == 0 || $value['sup_id'] == $sup_id){
                        $data['oil'][$value['oil_id']] = $value;
                    }
                }
                $data['oil'] = array_values($data['oil']);
            }
            return $data;
        });
    }
}
